import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import {
  Button,
  Input,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Tooltip,
  Upload,
  UploadFile
} from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { HiddenDangerObj, StatusObj } from '@/enum/safety';
import {
  safeHazardInfoDelete,
  safeHazardInfoDownloadTemplate,
  safeHazardInfoImport,
  safeHazardInfoPage,
  safeHazardInfoStatistics
} from '@/services/bizApi/anquanyinhuanxinxijiekou';

import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.SafeHazardInfoEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const [filter] = Filter.useForm();
  const fileList = useRef<UploadFile[]>([]);
  const [statisticsCondition, setStatisticsCondition] = useState('');

  const statistic = useRequest(
    async () => {
      const res = await safeHazardInfoStatistics();

      return res?.data || {};
    },
    {
      refreshDeps: []
    }
  );

  const statisticSearch = (condition: string) => () => {
    table.search.reset();
    if (statisticsCondition === condition) {
      setStatisticsCondition('');
    } else {
      setStatisticsCondition(condition);
    }
    table.search.submit();
  };

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await safeHazardInfoPage({
        ...formData,
        ...id,
        statisticsCondition,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    setStatisticsCondition('');
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const handleImport = useRequest(
    async () => {
      const formData = new FormData();
      formData.append('file', fileList.current[0].originFileObj as File);

      await safeHazardInfoImport({} as ArgumentsType<typeof safeHazardInfoImport>[0], {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: formData,
        timeout: 60000
      });

      store.app?.message.success('导入成功');
      table.search.submit();
    },
    {
      manual: true
    }
  );
  return (
    <>
      {/**统计 */}
      <Space size={16} style={{ marginBottom: '20px', fontWeight: 'bold', cursor: 'pointer' }}>
        <div
          onClick={statisticSearch('1')}
          style={{ color: statisticsCondition === '1' ? 'var(--ant-color-primary)' : '' }}
        >
          <span>总数：</span>
          <Text>{statistic.data?.value1 || 0}</Text>
        </div>
        <div
          onClick={statisticSearch('2')}
          style={{ color: statisticsCondition === '2' ? 'var(--ant-color-primary)' : '' }}
        >
          <span>未完成数：</span>
          <Text>{statistic.data?.value2 || 0}</Text>
        </div>
      </Space>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={async () => {
                  const res = await safeHazardInfoDownloadTemplate({
                    skipErrorHandler: true,
                    responseType: 'blob'
                  });
                  Saver.saveAs(res?.data, '隐患台账模板.xlsx');
                }}
                type="primary"
              >
                下载模板
              </Button>
            )}
            {permission.check() && (
              <Upload
                maxCount={1}
                accept=".xls,.xlsx"
                showUploadList={false}
                beforeUpload={() => false}
                fileList={fileList.current}
                onChange={(info) => {
                  fileList.current = info.fileList;
                  if (fileList.current.length) {
                    handleImport.run();
                  }
                }}
              >
                <Button type="primary">导入</Button>
              </Upload>
            )}
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="type">
          <Select
            style={{ width: 180 }}
            placeholder="请选择隐患类型"
            options={[
              {
                label: '安全隐患',
                value: 1
              },
              {
                label: '环保隐患',
                value: 2
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="inspectionUserName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入检查人员"
          />
        </Filter.Item>
        <Filter.Item name="inspectionUnitName">
          <Input
            style={{
              width: 180
            }}
            placeholder="请输入检查单位"
          />
        </Filter.Item>
        <Filter.Item name="status">
          <Select
            style={{ width: 180 }}
            placeholder="请选择状态"
            options={[
              {
                label: '待验收',
                value: 3
              },
              {
                label: '超时',
                value: 4
              },
              {
                label: '验收通过',
                value: 5
              },
              {
                label: '验收失败',
                value: 6
              }
            ]}
          />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          // {
          //   title: '隐患名称',
          //   dataIndex: 'name'
          // },
          {
            title: '隐患单号',
            dataIndex: 'no'
          },
          {
            title: '隐患内容',
            dataIndex: 'content',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          {
            title: '隐患类型',
            dataIndex: 'type',
            render: (v) => {
              const obj = HiddenDangerObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '检查人员',
            dataIndex: 'inspectionUserName'
          },
          {
            title: '检查单位',
            dataIndex: 'inspectionUnitName'
          },
          {
            title: '受检单位',
            dataIndex: 'inspectedUnitName'
          },
          {
            title: '创建人',
            dataIndex: 'createBy'
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (v) => dayjs(v).format('YYYY-MM-DD')
          },
          {
            title: '整改建议',
            dataIndex: 'suggestion',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          {
            title: '整改截止时间',
            dataIndex: 'dueTime',
            render: (v) => dayjs(v).format('YYYY-MM-DD')
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = StatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          // {
          //   title: '验收人',
          //   dataIndex: 'acceptanceUserName'
          // },
          {
            title: '验收时间',
            dataIndex: 'acceptanceTime',
            render: (v) => (v ? dayjs(v).format('YYYY-MM-DD') : '')
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() &&
                    (row?.status === 3 || row?.status === 4) &&
                    store.user?.id === row.inspectionUserId && (
                      <Text
                        onClick={() => {
                          dispose.current?.open({
                            rowData: row,
                            onSuccess: () => {
                              table.refresh();
                            }
                          });
                        }}
                        type="primary"
                      >
                        验收
                      </Text>
                    )}
                  {permission.check() && row?.status !== 5 && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}

                  {permission.check() && row?.status !== 5 && (
                    <Popconfirm
                      title={`确定删除吗？`}
                      onConfirm={async () => {
                        const res = await safeHazardInfoDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
    </>
  );
};

export default Page;
